import { defineStore } from "pinia";
import { ref } from "vue";
import { UserInfoTypes } from "@/types/user";
import { getInfo} from '@/api/login';

export const useUserStore = defineStore("user", () => {
  const userInfo = ref<UserInfoTypes | undefined>(uni.getStorageSync('userInfo')); // 用户信息

  /**
   * 获取，更新用户信息
   * @returns {Promise<any>}
  */
  async function getUserInfo() {
    const data = await getInfo();
    userInfo.value = data.user;
    uni.setStorageSync('userInfo', userInfo.value); // 持久化
  }

  /**
   *  退出登录
  */
  function logOut(callBackPage?: string) {
    uni.removeStorageSync('token');
    userInfo.value = undefined;
    uni.removeStorageSync('userInfo');
    
    uni.$u.route({
      type: 'reLaunch',
      url: '/pages/login/login',
      params: {
        callBackPage: callBackPage ?? uni.$u.page() // 退出登录前的页面,登录后跳转该页面
      }
    })
  }

  return {
    userInfo,
    getUserInfo,
    logOut
  };
});
